﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using BuildingTomorow;
using System.ComponentModel;
using System.Windows.Threading;
using Telerik.Windows.Controls;
using System.Threading;

namespace Testing_components
{
    /// <summary>
    /// Interaction logic for ChartsTab.xaml
    /// </summary>
    public partial class ChartsTab : UserControl
    {
        private DateTime fromTime;
        private DateTime toTime;
        private Image emptyImage;
        private bool _Average;

        ObservableCollection<PresentableGroup> sensors = new ObservableCollection<PresentableGroup>();
        private List<PresentableSensor> _SelectedSensors = new List<PresentableSensor>();
        public ChartsTab()
        {
            InitializeComponent();
            BackgroundWorker worker = new BackgroundWorker();
            worker.DoWork += delegate(object s, DoWorkEventArgs args)
                {
                        try
                        {
                            foreach (var item in DataAccess.GetInstance().GetGroups())
                            {
                                sensors.Add(new PresentableGroup(item));
                            }


                        }
                        catch
                        {

                        }
                        Application.Current.Dispatcher.BeginInvoke(
                        DispatcherPriority.Background,
                            new System.Action(() => radTreeView1.DataContext = sensors));
                        DateTime start = DataAccess.GetInstance().MinDate();
                        DateTime end = DataAccess.GetInstance().MaxDate();
                        Application.Current.Dispatcher.BeginInvoke(
                       DispatcherPriority.Background,
                           new System.Action(() =>
                           {

                               radDateTimePickerFrom.DisplayDateStart = start;
                               radDateTimePickerFrom.DisplayDateEnd = end;
                               radDateTimePickerTo.DisplayDateStart = start;
                               radDateTimePickerTo.DisplayDateEnd = end;
                           }
                           ));

                        Application.Current.Dispatcher.BeginInvoke(
                        DispatcherPriority.Background,
                            new System.Action(() => busyIndicatorCharts.IsBusy = false));

                };
            busyIndicatorCharts.IsBusy = true;
            worker.RunWorkerAsync();
            //sensors.Add(new Sensor { ID = 1, Description = "Bla", Group = "Wall 1", IconPath = "/Testing%20components;component/Images/cloudy.png", Name = "TP 1000", PresentableValue = "18C", Status = true, Type = "Temperarure", Value = 18, X = 2.2, Y = 3.1, Z = 1 });
            //sensors.Add(new Sensor { ID = 2, Description = "Bla2", Group = "Wall 1", IconPath = "/Testing%20components;component/Images/light-snow.png", Name = "TP 1001", PresentableValue = "18.7C", Status = true, Type = "Temperarure", Value = 18, X = 2.2, Y = 3.1, Z = 1 });
            //sensors.Add(new Sensor { ID = 3, Description = "Bla3", Group = "Wall 1", IconPath = "/Testing%20components;component/Images/light-snow.png", Name = "TP 1002", PresentableValue = "19C", Status = true, Type = "Temperarure", Value = 18, X = 2.2, Y = 3.1, Z = 1 });
            //sensors.Add(new Sensor { ID = 4, Description = "Bla4", Group = "Wall 2", IconPath = "/Testing%20components;component/Images/heavy-rain.png", Name = "TP 1003", PresentableValue = "2.6Pn", Status = true, Type = "Humidity", Value = 18, X = 2.2, Y = 3.1, Z = 1 });
            //sensors.Add(new Sensor { ID = 5, Description = "Bla5", Group = "Wall 2", IconPath = "/Testing%20components;component/Images/storm.png", Name = "TP 1004", PresentableValue = "60%", Status = false, Type = "Air Quality", Value = 18, X = 2.2, Y = 3.1, Z = 1 });
            //sensors.Add(new Sensor { ID = 6, Description = "Bla6", Group = "Wall 2", IconPath = "/Testing%20components;component/Images/sunny.png", Name = "TP 1005", PresentableValue = "5PSI", Status = true, Type = "Presure", Value = 18, X = 2.2, Y = 3.1, Z = 1 });

            emptyImage = new Image();
            emptyImage.MaxWidth = 600;
            emptyImage.Source = new BitmapImage(new Uri("/Testing%20components;component/Images/chart.png", UriKind.Relative));
            stackpanelChart.Children.Insert(0, emptyImage);
        }
        private void radDateTimePickerFrom_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            fromTime = (DateTime)radDateTimePickerFrom.SelectedValue;
        }

        private void radDateTimePickerTo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            toTime = (DateTime)radDateTimePickerTo.SelectedValue;
        }

        private void buttonUpdateCharts_Click(object sender, RoutedEventArgs e)
        {
            busyIndicatorRedrwing.IsBusy = true;
            //MessageBox.Show("From:" + fromTime.ToString("G", CultureInfo.CreateSpecificCulture("en-us")) + "\t\t To:" + toTime.ToString("G", CultureInfo.CreateSpecificCulture("en-us")));

            //if (stackpanelChart.Children.Contains(emptyImage))
            //{
            //    stackpanelChart.Children.Remove(emptyImage);
            //}
            //else
            //{
            //    stackpanelChart.Children.Add(emptyImage);
            //}

            reDrawCharts();
            //List<SensorDB> sens = DataAccess.GetInstance().GetSensors();
            //for (int i = 0; i < 26; i++)
            //{
            //    DateTime tim = DateTime.Parse("06/01/2012");
            //    SensorDB sss = sens[i];
            //    for (int j = 0; j < (14 * (24 * (60 / 15))); j++)
            //    {
            //        double temperarutereading = (new Random().NextDouble() * 4 + 18);
            //        SensorDataDB s = new SensorDataDB() { SensorID = sss.ID, TimeStamp = tim, Value = temperarutereading };
            //        tim = tim.AddMinutes(15);
            //        DataAccess.GetInstance().AddSensorData(s);
            //    }
            //}

               

        }

        private void checkboxGroupClicked_Click(object sender, RoutedEventArgs e)
        {
            busyIndicatorRedrwing.IsBusy = true;
            CheckBox GroupCheckbox = (CheckBox)sender;
            PresentableGroup group = GroupCheckbox.DataContext as PresentableGroup;
            foreach (var item in group.Sensors.Where(x => x.Status == true))
            {
                bool tmp = (bool)GroupCheckbox.IsChecked;

                if (tmp)
                {
                    if (!item.IsSensorSelected)
                    {
                        _SelectedSensors.Add(item);
                    }
                }
                else
                {
                    _SelectedSensors.Remove(item);
                }
                item.IsSensorSelected = tmp;
               
            }
            reDrawCharts();
        }

        private void checkboxSensorClicked_Click(object sender, RoutedEventArgs e)
        {
            busyIndicatorRedrwing.IsBusy = true;
            CheckBox SensorCheckbox = (CheckBox)sender;
            PresentableSensor sensor = SensorCheckbox.DataContext as PresentableSensor;
            if (!_SelectedSensors.Contains(sensor))
            {
                _SelectedSensors.Add(sensor);
                reDrawCharts();
            }
            else
            {
                _SelectedSensors.Remove(sensor);
                 reDrawCharts();
            }
        }
        private void reDrawCharts()
        {

            BackgroundWorker chartsMaker = new BackgroundWorker();
            chartsMaker.DoWork += new DoWorkEventHandler(chartsMaker_DoWork);
            chartsMaker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(chartsMaker_RunWorkerCompleted);
            chartsMaker.RunWorkerAsync();

        }

        void chartsMaker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            busyIndicatorRedrwing.IsBusy = false;
            List<ChartSensorGrouping> charts =(List<ChartSensorGrouping>) e.Result;
            foreach (var chart in charts)
            {
                chart.chart = new RadChart();
                chart.Prepare();
            }
            stackpanelChart.Children.Clear();
            if (charts.Count == 0)
            {
              
                stackpanelChart.Children.Add(emptyImage);
            }
            else
            {
                foreach (var chart in charts)
                {
                    stackpanelChart.Children.Add(chart.chart);
                }
            }
        }

        void chartsMaker_DoWork(object sender, DoWorkEventArgs e)
        {
            List<ChartSensorGrouping> charts = new List<ChartSensorGrouping>();

                    foreach (var item in _SelectedSensors)
                    {
                        if (charts.Any(x => x.Type == item.Type))
                        {
                            charts.Where(x => x.Type == item.Type).First().Sensors.Add(item);
                        }
                        else
                        {
                            List<PresentableSensor> tmpRef = new List<PresentableSensor>();
                            tmpRef.Add(item);

                            RadChart rc = null;

                            charts.Add(new ChartSensorGrouping() { Sensors = tmpRef, Type = item.Type, chart = rc });
                        }
                    }
                    foreach (var chart  in charts)
                    {
                        chart.PrepareSensors(fromTime, toTime, _Average);
                    }
                    e.Result = charts;

                    Thread.Sleep(1000);

        }


        private void checkboxAverage_Click(object sender, RoutedEventArgs e)
        {
            busyIndicatorRedrwing.IsBusy = true;
            _Average = (bool)checkboxAverage.IsChecked;
            reDrawCharts();
        }
    }
}
